package org.example.servlet;

import org.example.DAO.CommentDao;
import org.example.entity.Comment;
import org.example.entity.User;
import org.example.impl.CommentDaoImpl;
import org.example.Util.DataSourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/user-comments")
public class UserCommentsServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(UserCommentsServlet.class);
    private CommentDao commentDao;

    @Override
    public void init() throws ServletException {
        this.commentDao = new CommentDaoImpl(DataSourceUtil.getDataSource());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        HttpSession session = request.getSession(false);

        try {
            // 1. 验证用户登录状态
            if (session == null || session.getAttribute("user") == null) {
                response.sendRedirect("Userlogin.jsp?redirect=user-comments");
                return;
            }

            // 2. 获取当前用户
            User user = (User) session.getAttribute("user");
            logger.info("获取用户ID: {} 的评论", user.getId());

            // 3. 获取用户评论列表及相关内容信息
            List<Comment> userComments = commentDao.getCommentsWithContentByUser(user.getId());
            logger.info("获取到 {} 条评论", userComments.size());

            // 4. 设置请求属性
            request.setAttribute("userComments", userComments);

            // 5. 处理消息
            String successMessage = (String) request.getSession().getAttribute("commentSuccess");
            String errorMessage = (String) request.getSession().getAttribute("commentError");

            if (successMessage != null) {
                request.setAttribute("successMessage", successMessage);
                request.getSession().removeAttribute("commentSuccess");
            }

            if (errorMessage != null) {
                request.setAttribute("errorMessage", errorMessage);
                request.getSession().removeAttribute("commentError");
            }

            // 6. 转发到JSP页面
            request.getRequestDispatcher("userComments.jsp").forward(request, response);

        } catch (SQLException e) {
            logger.error("数据库错误", e);
            request.setAttribute("errorMessage", "获取评论失败，请稍后再试");
            request.getRequestDispatcher("userComments.jsp").forward(request, response);
        }
    }
}